package com.example.demo.controller;

import com.example.demo.service.EmailService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/email")
public class EmailController {

    @Resource
    private  EmailService emailService;

    @Autowired
    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/sendEmail")
    public boolean sendEmail(@RequestParam("email") String email) {
        System.out.println(email);
        //邮箱账号校验
        String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        Pattern pattern = Pattern.compile(EMAIL_REGEX);
        Matcher matcher = pattern.matcher(email);
        boolean result = matcher.matches();
        if (!result){
            System.out.println(1);
            return false;
        }
        //用随机数模拟验证码
        String randomNum = Integer.toString( new Random().nextInt(9000) + 1000);

        // 将验证码存入Redis
        redisTemplate.opsForValue().set("randomNum", randomNum,5, TimeUnit.MINUTES);
        String subject="邮箱验证码";
        String message="您的验证码是:"+randomNum+"，请妥善保管，切勿泄露,有效期是五分钟。";

        try {
            emailService.sendEmail(email, subject, message);
            return true;
        } catch (MessagingException | jakarta.mail.MessagingException e) {
            System.out.println(2);
            e.printStackTrace();
            return false;
        }
    }
}